import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

import 'logutil.dart';

// 本地存储
class SpUtil {
  SpUtil._internal(){
    if(prefs == null){
      init();
    }
  }
  static final SpUtil _instance = SpUtil._internal();

  factory SpUtil() {

    return _instance;

  }

  SharedPreferences? prefs;



  Future<void> init() async {
    prefs ??= await SharedPreferences.getInstance();
  }

  Future<bool> setJSON(String key, dynamic jsonVal) async{
    await init();
    String jsonString = jsonEncode(jsonVal);
    return prefs!.setString(key, jsonString);
  }

  Future<bool> setStr(String key, String value) async{
    await init();
    return prefs!.setString(key, value);
  }

  dynamic getJSON(String key) async{
    await init();
    String? jsonString = prefs?.getString(key);
    return jsonString == null ? null : jsonDecode(jsonString);
  }

  Future<String> getStr(String key) async{
    await init();
    String? str = prefs?.getString(key);

    return str ?? '';
  }

  Future<bool> setInt(String key, int value) async{
    return prefs!.setInt(key, value);
  }
  Future<int> getInt(String key) async{
    int? str = prefs?.getInt(key);

    return str ?? 0;
  }

  Future<bool> setBool(String key, bool val) async{
    return prefs!.setBool(key, val);
  }

  Future<bool?> getBool(String key) async{
    return prefs!.getBool(key);
  }

  Future<bool> remove(String key) async{
    return prefs!.remove(key);
  }
}

class StorageKeys {
  static const firstLaunch = 'firstLaunch';
}
